import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:moose_app/core/utils/navigate_util.dart';
import 'package:moose_app/ui/screens/chat/chat_screen.dart';
import 'package:moose_app/ui/values/values.dart';
import 'package:moose_app/ui/widgets/scroll/scroller_configuration_wrapper.dart';

import 'widget/message_item.dart';
import 'widget/message_type_icon.dart';

class ATHMessageBody extends StatefulWidget {
  @override
  _ATHMessageBodyState createState() => _ATHMessageBodyState();
}

class _ATHMessageBodyState extends State<ATHMessageBody>
    with SingleTickerProviderStateMixin {
  String _currentMessageType = 'message';

  String _currentMessageTitle = "私信";

  TabController _orderTabController;

  List<ATHMessageTypeModel> _messageTypes = [];

  EasyRefreshController _easyRefreshController;

  int _messageCount = 6;

  @override
  void initState() {
    super.initState();

    _messageTypes = [
      ATHMessageTypeModel(
        type: "notification",
        title: "通知",
        iconPath: "assets/icons/message/icon_message_notice.svg",
      ),
      ATHMessageTypeModel(
        type: "comment",
        title: "评论",
        iconPath: "assets/icons/message/icon_message_comment.svg",
      ),
      ATHMessageTypeModel(
        type: "message",
        title: "私信",
        iconPath: "assets/icons/message/icon_message_msg.svg",
      ),
      ATHMessageTypeModel(
        type: "hot_line",
        title: "客服",
        iconPath: "assets/icons/message/icon_message_hot_line.svg",
      )
    ];

    _easyRefreshController = EasyRefreshController();

    _orderTabController = TabController(
        initialIndex: 2, length: _messageTypes.length, vsync: this);

    _orderTabController
      ..addListener(() {
        print(_orderTabController.index);
        int index = _orderTabController.index;
        String currentTitle = _messageTypes[index].title;
        String currentType = _messageTypes[index].type;
        if (null != currentTitle) {
          this.setState(() {
            _currentMessageTitle = currentTitle;
            _currentMessageType = currentType;
          });
        }
      });
  }

  @override
  Widget build(BuildContext context) {
    return ATHScrollerConfigurationWrapper(
      child: Column(
        children: <Widget>[_buildMessageTopItem(), _buildMessageContent()],
      ),
    );
  }

  TabBarView _buildTabBarView() {
    return TabBarView(
      dragStartBehavior: DragStartBehavior.down,
      physics: NeverScrollableScrollPhysics(),
      controller: _orderTabController,
      children: _messageTypes.map((e) => _buildListView()).toList(),
    );
  }

  Widget _buildListView() {
    return EasyRefresh.custom(
        enableControlFinishRefresh: true,
        enableControlFinishLoad: true,
        controller: _easyRefreshController,
        header: MaterialHeader(),
        footer: MaterialFooter(),
        onRefresh: () async {
          await Future.delayed(Duration(seconds: 2), () {
            _easyRefreshController.finishRefresh(success: true);
            _easyRefreshController.resetRefreshState();
            setState(() {
              _messageCount += 2;
            });
          });
        },
        onLoad: () async {
          await Future.delayed(Duration(seconds: 2), () {
            setState(() {
              _messageCount += 2;
            });
            _easyRefreshController.finishLoad(noMore: _messageCount >= 10);
          });
        },
        slivers: [
          SliverList(
            delegate: SliverChildBuilderDelegate((context, index) {
              return ATHMessageItem(
                press: () {
                  _handleListItemPress(index);
                },
              );
            }, childCount: _messageCount),
          )
        ]);
  }

  Color _getCurrentColor(type) {
    return _currentMessageType == type ? kColorPrimaryLight : Colors.white;
  }

  void _setCurrentTabView(element) {
    int index = _messageTypes.indexOf(element);
    if (null != index) {
      _orderTabController.animateTo(index,
          duration: Duration(milliseconds: 100));
    }
  }

  void _setMessageIcon(type) {
    this.setState(() {
      _currentMessageType = type;
    });
  }

  void _setMessageTitle(title) {
    this.setState(() {
      _currentMessageTitle = title;
    });
  }

  void _handleListItemPress(index) {
//    showCupertinoModalBottomSheet(
//      expand: true,
//      context: context,
//      builder: (context, scrollController) =>
//          ATHMessageContentModal(scrollController: scrollController),
//    );
    ATHNavigator.pushFromRight(context, ATHChatScreen.routeName);
    print('点击了 $index');
  }

  Widget _buildMessageTopItem() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: kSize30),
      decoration: BoxDecoration(color: Colors.white, boxShadow: [
        BoxShadow(
            color: kColorE2,
            //阴影xy轴偏移量
            offset: Offset(0.0, 0.0),
            //阴影模糊程度
            blurRadius: kSize1,
            //阴影扩散程度
            spreadRadius: kSize1)
      ]),
      child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: _messageTypes
              .map((model) => ATHMessageTypeIcon(
                    svgPath: model.iconPath,
                    color: _getCurrentColor(model.type),
                    showReadDot: model.showReadDot,
                    press: () {
                      _setMessageIcon(model.type);
                      _setMessageTitle(model.title);

                      _setCurrentTabView(model);

                      _messageTypes[1].showReadDot = true;
                      this.setState(() {
                        _messageTypes = _messageTypes;
                      });
                    },
                  ))
              .toList()),
    );
  }

  Widget _buildMessageContent() {
    return Expanded(
      child: Container(
        margin: kCommonMarin,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              child: Text(
                _currentMessageTitle,
                style: TextStyle(
                    fontSize: kFontSize36,
                    fontWeight: FontWeight.w600,
                    color: kColor33),
              ),
            ),
            Expanded(child: _buildTabBarView())
          ],
        ),
      ),
    );
  }
}

class ATHMessageTypeModel {
  String type;
  String title;
  bool showReadDot;
  String iconPath;

  ATHMessageTypeModel(
      {this.type, this.title, this.showReadDot = false, this.iconPath});
}
